﻿using System;
using System.Linq;
using BusinessBingo.Data.Filter;
using BusinessBingo.Data.Interfaces;
using BusinessBingo.Model;
using BusinessBingo.Model.Interfaces;
using BusinessBingo.Queries;
using BusinessBingo.QueryHandlers.Base;
using BusinessBingo.QueryHandlers.Interfaces;
using BusinessBingo.QueryHandlers.Results;

namespace BusinessBingo.QueryHandlers
{
    public class GetLastGameOfGroupQueryHandler : BaseQueryHandler, IGetLastGameOfGroupQueryHandler
    {
        private IGameRepository _gameRepository;

        public GetLastGameOfGroupQueryHandler(
            IGameRepository gameRepository,
            IValidationState validationState) : base(validationState)
        {
            this._gameRepository = gameRepository;
        }

        public GetLastGameOfGroupQueryHandlerResult Execute(GetLastGameOfGroupQuery getLastGameOfGroupQuery)
        {
            GetLastGameOfGroupQueryHandlerResult result = new GetLastGameOfGroupQueryHandlerResult();

            if(getLastGameOfGroupQuery == default(GetLastGameOfGroupQuery))
                throw new ArgumentNullException("GetLastGameOfGroupQuery");
            if(getLastGameOfGroupQuery.GroupId == default(Guid))
                this._validationState.AddError<GetLastGameOfGroupQuery>(x => x.GroupId, ErrorTypes.Empty);

            if (this._validationState.IsValid == false)
                return result;

            GameFilter filter = new GameFilter();
            filter.WithGroupId = getLastGameOfGroupQuery.GroupId;
            filter.OnlyLastGame = true;

            Game game = this._gameRepository.GetItems(null, null, filter).SingleOrDefault();
            if (game == null)
                result.HasGames = false;
            else
            {
                result.HasGames = true;
                result.LastGame = game;
            }

            result.Succeeded = true;
            return result;
        }
    }
}